import { boot } from 'quasar/wrappers'
import axios from 'axios'
import { LocalStorage } from 'quasar'
import { authStore } from 'src/stores/auth-store'


const baseURL = process.env.APP_API_URL ?? 'http://77.240.38.191:8008'
const api = axios.create({ baseURL })

if (!api.defaults.baseURL) {
  api.defaults.baseURL = '/api'
}

export default boot(async ({ app, router }) => {
  api.defaults.withCredentials = true

  app.config.globalProperties.$axios = axios
  app.config.globalProperties.$api = api

  const apiToken = LocalStorage.getItem('token')
  if (apiToken) {
    api.defaults.headers.common.Authorization = 'Bearer ' + apiToken
  }

  api.interceptors.response.use(response => {
    return response
  }, async error => {
    if (error.response && error.response.status === 401) {
      const auth = authStore()
      auth.logout()
      if (router.currentRoute.value.path !== '/login') {
        await router.push({ name: 'login' })
      }
    }
    return Promise.reject(error)
  })
})

export { api }
